package com.guqj.nio.netty.ex;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class TimeClientHandler extends SimpleChannelInboundHandler<Object> {

	private ByteBuf firstMessgae;
	private int flag = 0;
	
	public TimeClientHandler() {
		byte[] req = "QUERY TIME ORDER".getBytes();
		firstMessgae = Unpooled.buffer(req.length);
		firstMessgae.writeBytes(req);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("客户已连接服务端");
		ctx.writeAndFlush(firstMessgae);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("客户端收到服务器响应数据");
		ByteBuf buf = (ByteBuf) msg;
		byte[] bytes = new byte[buf.readableBytes()];
		buf.readBytes(bytes);
		String body = new String(bytes, "UTF-8");
		System.out.println("the time client receive order [" + body + "]");
		String res = "O(∩_∩)O好的" + (++flag);
		/*ByteBuf f = Unpooled.copiedBuffer(res.getBytes());
		ctx.writeAndFlush(f);*/
		System.out.println("客户端回复了服务端");
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
		System.out.println("客户端flush");
	}

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("messageReceived");
	}

}
